<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>DTO - Oatpp教程</title>
        <!-- Custom HTML head -->
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">
        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">
        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="DTO.html" class="active"><strong aria-hidden="true">1.</strong> DTO</a></li><li class="chapter-item expanded "><a href="Async概述.html"><strong aria-hidden="true">2.</strong> Async</a></li><li class="chapter-item expanded "><a href="Simple_vs_Async.html"><strong aria-hidden="true">3.</strong> Simple vs Async</a></li><li class="chapter-item expanded "><a href="协程.html"><strong aria-hidden="true">4.</strong> 协程</a></li><li class="chapter-item expanded "><a href="关系型对象映射框架.html"><strong aria-hidden="true">5.</strong> ORM</a></li><li class="chapter-item expanded "><a href="Monolithization.html"><strong aria-hidden="true">6.</strong> Monolithization</a></li><li class="chapter-item expanded "><a href="步骤指南.html"><strong aria-hidden="true">7.</strong> 步骤指南</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Oatpp教程</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="dto"><a class="header" href="#dto">DTO</a></h1>
<p>DTO是继承于<code>oatpp::DTO</code> 的对象，用于序列化和反序列化<code>oatpp::data::mapping::ObjectMapper</code> 的一个特殊对象</p>
<h2 id="介绍"><a class="header" href="#介绍">介绍</a></h2>
<p>DTO对象采用DTO代码创建块创建，必须从<code>#include OATPP_CODEGEN_BEGIN(DTO)</code> 开始，以<code>#include OATPP_CODEGEN_END(DTO)</code> 结束，<em>不要忘记关闭代码创建块，防止接下来的代码产生宏冲突</em></p>
<pre><code class="language-text-x-c-src">#include &quot;oatpp/core/Types.hpp&quot;
#include &quot;oatpp/core/macro/codegen.hpp&quot;

#include OATPP_CODEGEN_BEGIN(DTO) ///&lt; Begin DTO codegen section

class User : public oatpp::DTO {

  DTO_INIT(User, DTO /* extends */)

  DTO_FIELD(String, name);
  DTO_FIELD(Int32, age);

};

#include OATPP_CODEGEN_END(DTO) ///&lt; End DTO codegen section
</code></pre>
<h2 id="字段名修饰"><a class="header" href="#字段名修饰">字段名修饰</a></h2>
<pre><code class="language-text-x-c-src">DTO_FIELD(String, name, &quot;user-name&quot;);
</code></pre>
<h3 id="默认值"><a class="header" href="#默认值">默认值</a></h3>
<p>默认所有值都设置为nullptr,你可以分配一个值来覆盖DTO字段的默认值</p>
<pre><code class="language-text-x-c-src">DTO_FIELD(String, name) = &quot;Ivan&quot;;
</code></pre>
<h3 id="添加字段信息"><a class="header" href="#添加字段信息">添加字段信息</a></h3>
<pre><code class="language-text-x-c-src">DTO_FIELD_INFO(name) {
  info-&gt;description = &quot;user first name&quot;; //在Swagger-UI中加入该字段的描述
}
DTO_FIELD(String, name) = &quot;Ivan&quot;
</code></pre>
<h3 id="声明字段是一个对象"><a class="header" href="#声明字段是一个对象">声明字段是一个对象</a></h3>
<pre><code class="language-text-x-c-src">DTO_FIELD(Object&lt;User&gt;, user);
</code></pre>
<h3 id="声明字段是一个列表"><a class="header" href="#声明字段是一个列表">声明字段是一个列表</a></h3>
<p>基本类型列表</p>
<pre><code class="language-text-x-c-src">DTO_FIELD(List&lt;Int32&gt;, colors);
</code></pre>
<p>对象列表</p>
<pre><code class="language-text-x-c-src">DTO_FIELD(List&lt;Object&lt;MyObject&gt;&gt;, colors);
</code></pre>
<h3 id="声明字段是一个map"><a class="header" href="#声明字段是一个map">声明字段是一个Map</a></h3>
<p>Map <code>String – &gt; Int32</code></p>
<pre><code class="language-text-x-c-src">DTO_FIELD(Fields&lt;Int32&gt;, colors);
</code></pre>
<p>Map <code>String – &gt; Object</code></p>
<pre><code class="language-text-x-c-src">DTO_FIELD(Fields&lt;Object&lt;MyObject&gt;&gt;, colors);
</code></pre>
<h2 id="类型"><a class="header" href="#类型">类型</a></h2>
<h3 id="核心类型"><a class="header" href="#核心类型">核心类型</a></h3>
<p>这些类型定义在<code>oatpp/core/Types.cpp</code></p>
<p><strong>基础类型</strong></p>
<div class="table-wrapper"><table><thead><tr><th></th><th></th><th></th></tr></thead><tbody>
<tr><td>Type</td><td>Underlying</td><td>Default Value</td></tr>
<tr><td>Int8</td><td>v_int8</td><td>nullptr</td></tr>
<tr><td>UInt8</td><td>v_uint8</td><td>nullptr</td></tr>
<tr><td>Int16</td><td>v_int16</td><td>nullptr</td></tr>
<tr><td>UInt16</td><td>v_uint16</td><td>nullptr</td></tr>
<tr><td>Int32</td><td>v_int32</td><td>nullptr</td></tr>
<tr><td>UInt32</td><td>v_uint32</td><td>nullptr</td></tr>
<tr><td>Int64</td><td>v_int64</td><td>nullptr</td></tr>
<tr><td>UInt64</td><td>v_uint64</td><td>nullptr</td></tr>
<tr><td>Float32</td><td>v_float32</td><td>nullptr</td></tr>
<tr><td>Float64</td><td>v_float64</td><td>nullptr</td></tr>
<tr><td>Boolean</td><td>bool</td><td>nullptr</td></tr>
</tbody></table>
</div>
<p>示例</p>
<pre><code class="language-text-x-c-src">oatpp::Int32 a = 32;
v_int32 va = *a;
</code></pre>
<p><strong>集合</strong></p>
<div class="table-wrapper"><table><thead><tr><th></th><th></th><th></th></tr></thead><tbody>
<tr><td>Type</td><td>Underlying Collection</td><td>Default Value</td></tr>
<tr><td>Vector<T></td><td>std::vector<T></td><td>nullptr</td></tr>
<tr><td>List<T></td><td>std::list<T></td><td>nullptr</td></tr>
<tr><td>UnorderedSet</td><td>std::unordered_set<T></td><td>nullptr</td></tr>
<tr><td>Fields<T></td><td>std::list&lt;std::pair&lt;Key,Value&gt;&gt;</td><td>nullptr</td></tr>
<tr><td>UnorderedFields<T></td><td>std::unordered_map&lt;key,value&gt;</td><td>nullptr</td></tr>
</tbody></table>
</div>
<p>示例</p>
<pre><code class="language-text-x-c-src">oatpp::Vector&lt;oatpp::String&gt; porridges = {&quot;Owsianka&quot;, &quot;Stirabout&quot;, &quot;Zabkása&quot;};
for(auto&amp; porridge : *porridges) {
  ...
}
</code></pre>
<p><strong>特殊类型</strong></p>
<div class="table-wrapper"><table><thead><tr><th></th><th></th><th></th></tr></thead><tbody>
<tr><td>Type</td><td>Underlying Type</td><td>Default Value</td></tr>
<tr><td>String</td><td>oatpp::base::StrBuffer</td><td>nullptr</td></tr>
<tr><td>Object<T></td><td>从oatpp::DTO中继承而来</td><td>nullptr</td></tr>
<tr><td>Enum<T></td><td>通过enum声明</td><td>nullptr</td></tr>
<tr><td>Any</td><td>任何可使用映射的类型</td><td>nullptr</td></tr>
</tbody></table>
</div>
<p>示例</p>
<pre><code class="language-text-x-c-src">oatpp::Object&lt;MyDto&gt; dto = MyDto::createShared();
oatpp::Any any = dto;
...
auto dto = any.retrieve&lt;oatpp::Object&lt;MyDto&gt;&gt;(); //如果存储的类型不匹配会抛出std::runtime_error异常
</code></pre>
<h3 id="自定义类型"><a class="header" href="#自定义类型">自定义类型</a></h3>
<p>为了简化将自定义类型结合到oatpp的ObjectMapping框架中，这里引入<strong>Type Interpretation</strong>特性</p>
<p>现在你有一些结构体，但是还未结合到oatpp的对象框架中</p>
<pre><code class="language-text-x-c-src">struct VPoint {
  v_int32 x;
  v_int32 y;
  v_int32 z;
};
</code></pre>
<p>要将其合并你可以根据下面的代码</p>
<pre><code class="language-text-x-c-src">namespace __class {
  class PointClass;
}

//在你的类型中声明ObjectWrapper，这里类型别名为Point
typedef oatpp::data::mapping::type::Primitive&lt;VPoint, __class::PointClass&gt; Point;

namespace __class {

  //类型信息
  class PointClass {
  private:

	//类型声明
    class Inter : public oatpp::Type::Interpretation&lt;Point, oatpp::UnorderedFields&lt;oatpp::Int32&gt;&gt;  {
    public:

      oatpp::UnorderedFields&lt;oatpp::Int32&gt; interpret(const Point&amp; value) const override {
          return {{&quot;x&quot;, value-&gt;x}, {&quot;y&quot;, value-&gt;y}, {&quot;z&quot;, value-&gt;z}};
      }

      Point reproduce(const oatpp::UnorderedFields&lt;oatpp::Int32&gt; map) const override {
        return Point({map[&quot;x&quot;], map[&quot;y&quot;], map[&quot;z&quot;]});
      }

    };

  public:

    static const oatpp::ClassId CLASS_ID;

    static oatpp::Type* getType(){
      static Type type(CLASS_ID, nullptr, nullptr, {{&quot;my-types&quot;, new Inter()}} /*添加类型声明*/ );
      return &amp;type;
    }

  };

  const oatpp::ClassId PointClass::CLASS_ID(&quot;my-types::Point&quot;);

}
</code></pre>
<p>现在Point对象可以在对象映射中序列化/反序列化</p>
<pre><code class="language-text-x-c-src">oatpp::parser::json::mapping::ObjectMapper mapper;

{
  auto config = mapper.getSerializer()-&gt;getConfig();
  config-&gt;enabledInterpretations = {&quot;my-types&quot;}; //使能序列化
}

{
  auto config = mapper.getDeserializer()-&gt;getConfig();
  config-&gt;enabledInterpretations = {&quot;my-types&quot;}; //使能反序列化
}

Point point ({1, 2, 3}); //创建对象Point

auto json = mapper.writeToString(point); //序列化Point
auto pointClone = mapper.readFromString&lt;Point&gt;(json); //反序列化Point
</code></pre>
<blockquote>
<p>类型可以融合进所有的框架组件中，包括REST 框架，ORM，Swagger-UI</p>
</blockquote>
<h2 id="例子"><a class="header" href="#例子">例子</a></h2>
<h3 id="序列化反序列化"><a class="header" href="#序列化反序列化">序列化/反序列化</a></h3>
<p><strong>定义DTO</strong></p>
<pre><code class="language-text-x-c-src">#include &quot;oatpp/core/Types.hpp&quot;
#include &quot;oatpp/core/macro/codegen.hpp&quot;

#include OATPP_CODEGEN_BEGIN(DTO) //开始DTO代码创建段

class User : public oatpp::DTO {

  DTO_INIT(User, DTO /*基类*/)

  DTO_FIELD(String, name, &quot;First-Name&quot;);
  DTO_FIELD(String, surname, &quot;Family-Name&quot;);
  DTO_FIELD(Int32, age);
  DTO_FIELD(Fields&lt;List&lt;Object&lt;User&gt;&gt;&gt;, familyMembers); ///&lt; Map&lt;String, List&lt;User&gt;&gt;
  DTO_FIELD(Fields&lt;String&gt;, additionalNotes); ///&lt; Map&lt;String, String&gt;

};

#include OATPP_CODEGEN_END(DTO) //结束DTO代码创建段
</code></pre>
<p><strong>创建对象和设置字段</strong></p>
<pre><code class="language-text-x-c-src">//创建User对象
auto user = User::createShared();
user-&gt;name = &quot;Ivan&quot;;
user-&gt;surname = &quot;Ovsyanochka&quot;;
user-&gt;age = 24;
user-&gt;familyMembers = {}; //初始化空的Map容器
user-&gt;additionalNotes = {}; //初始化空的Map容器

auto brother = User::createShared();
brother-&gt;name = &quot;Yuriy&quot;;
brother-&gt;surname = &quot;Ovsyanochka&quot;;
brother-&gt;age = 30;

auto sister = User::createShared();
sister-&gt;name = &quot;Kate&quot;;
sister-&gt;surname = &quot;Ovsyanochka&quot;;
sister-&gt;age = 20;

//创建siblings列表
oatpp::List&lt;oatpp::Object&lt;User&gt;&gt; siblings = {brother, sister};

user-&gt;familyMembers-&gt;push_back({&quot;siblings&quot;, siblings});
user-&gt;additionalNotes-&gt;push_back({&quot;Education&quot;, &quot;Master of Computer Science&quot;});
</code></pre>
<p><strong>创建JSON对象映射</strong></p>
<pre><code class="language-text-x-c-src">#include &quot;oatpp/parser/json/mapping/ObjectMapper.hpp&quot;

...

//采用默认配置创建json的ObjectMapper
auto jsonObjectMapper = oatpp::parser::json::mapping::ObjectMapper::createShared();
</code></pre>
<p><strong>序列化user对象到JSON</strong></p>
<pre><code class="language-text-x-c-src">oatpp::String json = jsonObjectMapper-&gt;writeToString(user); 
OATPP_LOGD(&quot;json&quot;, &quot;value='%s'&quot;, json-&gt;c_str()); //打印JSON
</code></pre>
<p>输出:</p>
<pre><code class="language-application-json">{
  &quot;First-Name&quot;: &quot;Ivan&quot;,
  &quot;Family-Name&quot;: &quot;Ovsyanochka&quot;,
  &quot;age&quot;: 24,
  &quot;familyMembers&quot;: {
    &quot;siblings&quot;: [
      {
        &quot;First-Name&quot;: &quot;Yuriy&quot;,
        &quot;Family-Name&quot;: &quot;Ovsyanochka&quot;,
        &quot;age&quot;: 30,
        &quot;familyMembers&quot;: null,
        &quot;additionalNotes&quot;: null
      },
      {
        &quot;First-Name&quot;: &quot;Kate&quot;,
        &quot;Family-Name&quot;: &quot;Ovsyanochka&quot;,
        &quot;age&quot;: 20,
        &quot;familyMembers&quot;: null,
        &quot;additionalNotes&quot;: null
      }
    ]
  },
  &quot;additionalNotes&quot;: {
    &quot;Education&quot;: &quot;Master of Computer Science&quot;
  }
}
</code></pre>
<blockquote>
<p>如果需要更好的输出可以使用<code>oatpp::parser::json::Beautifier</code></p>
</blockquote>
<p>反序列化字符串</p>
<pre><code class="language-text-x-c-src">auto cloneOfUser = jsonObjectMapper-&gt;readFromString&lt;oatpp::Object&lt;User&gt;&gt;(json);
</code></pre>
<h3 id="使用json美化器"><a class="header" href="#使用json美化器">使用JSON美化器</a></h3>
<p>不使用美化器时，输出是没有空格和换行符的</p>
<pre><code class="language-text-x-c-src">{&quot;First-Name&quot;:&quot;Ivan&quot;,&quot;Family-Name&quot;:&quot;Ovsyanochka&quot;,&quot;age&quot;:24 ...
</code></pre>
<p>为了美化json，需要在设置中设置<code>useBeautifier = true</code> 在序列化配置中：</p>
<pre><code class="language-text-x-c-src">//创建序列化和反序列化配置
auto serializeConfig = oatpp::parser::json::mapping::Serializer::Config::createShared();
auto deserializeConfig = oatpp::parser::json::mapping::Deserializer::Config::createShared();

//启动美化器
serializeConfig-&gt;useBeautifier = true;

//采用序列化配置创建JSON对象映射
auto jsonObjectMapper = oatpp::parser::json::mapping::ObjectMapper::createShared(serializeConfig, deserializeConfig);
</code></pre>
<p>更多关于json对象映射的配置可以看这些:</p>
<p><a href="https://oatpp.io/api/latest/oatpp/parser/json/mapping/Serializer/#serializer-config">Serializer::Config</a></p>
<p><a href="https://oatpp.io/api/latest/oatpp/parser/json/mapping/Deserializer/#deserializer-config">Deserializer::Config</a></p>
<h2 id="代码示例"><a class="header" href="#代码示例">代码示例</a></h2>
<p> <a href="https://github.com/oatpp/oatpp-consul/blob/master/src/oatpp-consul/rest/DTOs.hpp">https://github.com/oatpp/oatpp-consul/blob/master/src/oatpp-consul/rest/DTOs.hpp</a></p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="next" href="Async概述.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="next" href="Async概述.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>

        <!-- Livereload script (if served using the cli tool) -->
        <script>
            const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsAddress = wsProtocol + "//" + location.host + "/" + "__livereload";
            const socket = new WebSocket(wsAddress);
            socket.onmessage = function (event) {
                if (event.data === "reload") {
                    socket.close();
                    location.reload();
                }
            };

            window.onbeforeunload = function() {
                socket.close();
            }
        </script>
        <script>
            window.playground_copyable = true;
        </script>
        <script src="elasticlunr.min.js"></script>
        <script src="mark.min.js"></script>
        <script src="searcher.js"></script>
        <script src="clipboard.min.js"></script>
        <script src="highlight.js"></script>
        <script src="book.js"></script>

        <!-- Custom JS scripts -->
    </body>
</html>
